package db;

import org.junit.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import utils.CommonUtils;

import java.io.IOException;
import java.util.Properties;

/**
 * Redis连接池
 */
public class JedisDBPool {

    public static JedisPool jedisPool;

    static {
        try {
            Properties properties = CommonUtils.readPropertiesFile("redis.properties");
            JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
            jedisPoolConfig.setMaxTotal(Integer.valueOf(properties.getProperty("maxTotal")));
            jedisPoolConfig.setMaxIdle(Integer.valueOf(properties.getProperty("maxIdle")));
            jedisPoolConfig.setMinIdle(Integer.valueOf(properties.getProperty("minIdle")));
            jedisPoolConfig.setMaxWaitMillis(Integer.valueOf(properties.getProperty("maxWaitMillis")));
            jedisPoolConfig.setTestOnBorrow(Boolean.valueOf(properties.getProperty("testOnBorrow")));
            jedisPoolConfig.setTestOnReturn(Boolean.valueOf(properties.getProperty("testOnReturn")));
            jedisPoolConfig.setTimeBetweenEvictionRunsMillis(Integer.valueOf(properties.getProperty("timeBetweenEvictionRunsMillis")));
            jedisPoolConfig.setMinEvictableIdleTimeMillis(Integer.valueOf(properties.getProperty("minEvictableIdleTimeMillis")));
            jedisPoolConfig.setNumTestsPerEvictionRun(Integer.valueOf(properties.getProperty("numTestsPerEvictionRun")));
            jedisPool = new JedisPool(jedisPoolConfig,properties.getProperty("host"),Integer.valueOf(properties.getProperty("port")));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static Jedis getConnectJedis() {
        return jedisPool.getResource();
    }

    public static boolean initConnection() {
        Jedis jedis = jedisPool.getResource();
        String pong = jedis.ping();
        jedis.close();
        if ("PONG".equals(pong)) {
            System.out.println("Redis数据库已连接");
            return true;
        } else {
            System.out.println("Redis数据库连接失败");
            return false;
        }
    }

    @Test
    public static void main(String[] args) {
        Jedis jedis = getConnectJedis();
        jedis.close();
    }
}
